package org.quipu.client;

import org.quipu.client.events.AppEventBus;
import org.quipu.client.events.BookSelectionChangedEvent;
import org.quipu.client.events.BooksOutOfDateEvent;
import org.quipu.dto.BookDto;

public class BookListBox extends AppListBox {

    public BookListBox(AppEventBus eventBus, AppCache cache, Long selectedBookId) {
        super(eventBus, cache, BooksOutOfDateEvent.class, new BookSelectionChangedEvent(), selectedBookId);
        getListBox().addStyleName("booksList");
        refresh();
    }

    @Override
    protected final void refresh() {
        getListBox().clear();
        int selectedIndex = -1;
        int i = 1;
        getListBox().addItem("", "0");
        for(BookDto book : getCache().getBooks()) {
            getListBox().addItem(book.getTitle(), String.valueOf(book.getId()));
            if(book.getId().equals(getSelectedId())) {
                selectedIndex = i;
            }
            i++;
        }
        if(selectedIndex < 0) {
            setSelectedId(null);
        } else {
            getListBox().setSelectedIndex(selectedIndex);
        }
    }
}
